<?php

namespace App\Http\Middleware;

use App\Model\Rules;
use App\Model\RulesGroup;
use App\Model\RulesGroupDetail;
use App\Tool\Doctrine;
use App\Tool\Json;
use Closure;
use Nette\Reflection\ClassType;

class checkAuth
{
    /**
     * Create by Peter
     * 2019/08/27 17:02:55
     * Email:904801074@qq.com
     * @param $request
     * @param Closure $next
     * @return \Illuminate\Http\JsonResponse|mixed
     * @throws \ReflectionException
     */
    public function handle($request, Closure $next)
    {

        $route = $request->route();

        $controller = $route->action['controller'];

        $c = explode('@', $controller);

        $class = new ClassType($c[0]);

        $data = $class->getMethod($c[1])->getAnnotation('Auth');

//        return response()->json($data);

        //无验证标记
        if ($data['type'] == 'no_check') return $next($request);

        $admin_id = resolve('adminInfo')['id'];

        $detail = RulesGroupDetail::where('uid', $admin_id)->first();

        if (!$detail) return response()->json(Json::codeArray(14, '该管理员未绑定角色'));

        $group_id = $detail->rules_group_id;

        //超级管理员
        if ($group_id === 0) {

            app()->instance('allRule', true);

            return $next($request);
        }


        $group = RulesGroup::find($group_id);

        if (!$group) return response()->json(Json::codeArray(15, '该管理员未找到路由规则'));

        $rule_list = $group['rules'];

        if (count($rule_list) <= 0) return response()->json(Json::codeArray(16, '该角色拥有的权限数小于1'));

        $rules = Rules::whereIn('id', $rule_list)->get();

        if (!$rules) return response()->json(Json::codeArray(16, '该角色拥有的权限数小于1'));

        $rules = array_column($rules->toArray(), 'rule');

        app()->instance('allRule', $rules);

        //是否有权限跳出标记
        if ($data['type'] == 'skip_auth') return $next($request);

        //判断依附权限
        if($data['type']=='attach'){

            $value=$data['value'];

            $attachList=explode(',',$value);

            foreach ($rules as $k=>$v){

                if(in_array($v,$attachList)) return $next($request);

            }

        }

        $currentRoute='/'.$route->uri;

        if(!in_array($currentRoute,$rules)) return response()->json(Json::codeArray(51, '你没有该权限'));

        return $next($request);
    }
}
